using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading.Tasks;
using Common.Net;
using Common.Tools;
using UnityEngine;

public partial class UClient : SingleTon<UClient>
{
    TcpClient tcpClient;
    TcpPack tcpPack = new TcpPack();
    NetworkStream stream;
    public static event Action<MsgInfo> HandlerController;

    public Queue<MsgInfo> delayMsgInfo = new Queue<MsgInfo>();

    public void Connect()
    {
        StartTcp();
    }

    void StartTcp()
    {
        tcpClient = new TcpClient();
        Task.Run(async () =>
        {
            int count = 0;
            while (tcpClient.Connected == false && count < 5)
            {
                try
                {
                    await tcpClient.ConnectAsync("127.0.0.1", 6688);
                }
                catch (System.Exception e)
                {
                    Debug.Log("Connect failed, retrying... " + e.Message);
                    count++;
                    await Task.Delay(500);
                }
            }
            if (tcpClient.Connected)
            {
                Debug.Log("Connected to server");
                RecieveTcpData();
            }
            else
            {
                Debug.Log("Connect failed");
            }
        });
    }

    /// <summary>
    /// 接受tcp数据
    /// </summary>
    void RecieveTcpData()
    {
        stream = tcpClient.GetStream();
        try
        {
            while (true)
            {
                int bytesRead = stream.Read(tcpPack.Data, tcpPack.StartIndex, tcpPack.RemainSize);
                tcpPack.ReceiveData(bytesRead, HanleTcpMsgInfo);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    void HanleTcpMsgInfo(RequestType type, object vo)
    {
        lock (delayMsgInfo)
        {
            Debug.Log("[收到服务器的数据了]");
            delayMsgInfo.Enqueue(new MsgInfo() { requestType = type, vo = vo });
        }
    }

    /// <summary>
    /// 派发消息
    /// </summary>
    public void Dispatch()
    {
        lock (delayMsgInfo)
        {
            if (delayMsgInfo.Count > 0)
            {
                var list = delayMsgInfo.ToArray();
                delayMsgInfo.Clear();
                foreach (var msgInfo in list)
                {
                    HandlerController?.Invoke(msgInfo);
                }
            }
        }
    }

    /// <summary>
    /// 默认通过tcp发送请求
    /// </summary>
    /// <param name="msg"></param>
    /// <exception cref="NotImplementedException"></exception>
    public void Send(MsgInfo msg)
    {
        byte[] data = TcpPack.WriteData(msg);
        stream.Write(data, 0, data.Length);
    }

    /// <summary>
    /// 断掉连接
    /// </summary>
    public void Disconnect()
    {
        if (tcpClient == null || !tcpClient.Connected)
            return;
        //发送给服务器，通知离线
        Send(new MsgInfo() { requestType = RequestType.ShutDown, });

        stream.Close();
        tcpClient.Close();

        // CloseUdp();
    }
}
